class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int left = (nums1.size() + nums2.size() + 1) / 2;
        int right = (nums1.size() + nums2.size() + 2) / 2;
        return (findmid(nums1, nums2, 0, 0, left) + findmid(nums1, nums2, 0, 0, right)) / 2;
    }

    double findmid(vector<int>& arr1, vector<int>& arr2, int i, int j, int k) {
        if (i >= arr1.size()) {
            return arr2[j + k - 1];
        }
        if (j >= arr2.size()) {
            return arr1[i + k - 1];
        }
        if (k == 1) { return min(arr1[i], arr2[j]); }

        int mid1 = 0;
        int mid2 = 0;
        if (i + k / 2 - 1 < arr1.size()) {
            mid1 = arr1[i + k / 2 - 1];
        }
        else {
            mid1 = INT_MAX;
        }
        if (j + k / 2 - 1 < arr2.size()) {
            mid2 = arr2[j + k / 2 - 1];
        }
        else {
            mid2 = INT_MAX;
        }

        if (mid1 < mid2) {
            return findmid(arr1, arr2, i + k / 2, j, k - k / 2);
        }
        else {
            return findmid(arr1, arr2, i, j + k / 2, k - k / 2);
        }
    }
};